""" 

    Story.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which posts stories to your profile.
    A user must be logged into Facebook to use this service.
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from facebook import FacebookError
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserLikes

class MainHandler(webapp.RequestHandler):
    
    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":""}
        
        try:
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "not logged in"
            else:
                uid = int(self.facebookapi.uid)
                message = self.request.get('message', default_value=None)
                story = self.request.get('story', default_value=None)
                link = self.request.get('link', default_value=None)
                
                if (message is None) or (story is None):
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "missing parameters"
                else: 
                    fbStory = {"message": message}
                    if story == "profile":
                        self.facebookapi.feed.publishUserAction("54914257770", fbStory)
                        jsonOutput["message"] = "Your profile has been updated."
                    elif story == "status":
                        self.facebookapi.status.set(message)
                        jsonOutput["message"] = "Your status has been updated."
                    elif story == "links":
                        self.facebookapi.links.post(self.facebookapi.uid, link, message)
                        jsonOutput["message"] = "The link has been added to your profile."
                        
            
        except FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput))          
  
def main():
	application = webapp.WSGIApplication([('/fb/story', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
